/**
 * 
 */
package com.feib.stms.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.feib.stms.model.ActionLog;
import com.feib.stms.model.User;
import com.feib.stms.service.ActionLogService;
import com.feib.stms.util.MenuLoader;
import com.feib.stms.util.SpringContextUtil;
import com.feib.stms.util.UserUtil;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.ExecutionContext;
import net.sourceforge.stripes.controller.Interceptor;
import net.sourceforge.stripes.controller.Intercepts;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.util.HttpUtil;

/**
 * @title (#)ActionLogInterceptor.java<br>
 * @description 畫面操作紀錄Interceptor<br>
 * @author Jimmy Liu<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2010/11/1 create by Jimmy Liu<br>
 */
@Intercepts( { LifecycleStage.RequestInit, LifecycleStage.ActionBeanResolution, LifecycleStage.HandlerResolution, LifecycleStage.RequestComplete })
public class ActionLogInterceptor implements Interceptor 
{
    public final static String ACCESS_LOG_KEY = "__STMS_ACCESS_LOG_KEY";
    
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    
    private MenuLoader menuLoader;
    
    public ActionLogInterceptor()
    {
    	menuLoader = (MenuLoader)SpringContextUtil.getBean("menuLoader");
    }

	/* (non-Javadoc)
	 * @see net.sourceforge.stripes.controller.Interceptor#intercept(net.sourceforge.stripes.controller.ExecutionContext)
	 */
	public Resolution intercept(ExecutionContext context) throws Exception 
	{			
			ActionBeanContext actionBeanContext = context.getActionBeanContext();
	        HttpServletRequest request = actionBeanContext.getRequest();
			
			ActionLog actionLog = (ActionLog)request.getAttribute(ACCESS_LOG_KEY);
			if (null == actionLog)
			{
				actionLog = new ActionLog();
				request.setAttribute(ACCESS_LOG_KEY, actionLog);
				
				User user =  UserUtil.getUser();
				if (null != user)
	            {
	                actionLog.setUserPk(user.getUserPk());
	                actionLog.setUserId(user.getUserId());
	                actionLog.setUserName(user.getUserName());
	                actionLog.setGroupNo(user.getGroup().getGroupNo());
	                actionLog.setGroupPk(user.getGroup().getGroupPk());
	                actionLog.setGroupName(user.getGroup().getGroupName());
	                if (null != user.getSecurities())
	                	actionLog.setSecurities(user.getSecurities());
	            }
			}
			
			if (LifecycleStage.RequestInit.equals(context.getLifecycleStage()))
			{
				// Request 起始階段
				String requestPath = HttpUtil.getRequestedPath(request); // ex:/Stms1001.action
				actionLog.setRequestPath(requestPath);
				actionLog.setRemoteAddr(request.getRemoteAddr());
				actionLog.setInDateTime(new Date());
			}
			else if (LifecycleStage.RequestComplete.equals(context.getLifecycleStage()))
	        {
	            actionLog.setOutDateTime(new Date());
	            log(actionLog);
	            request.removeAttribute(ACCESS_LOG_KEY);
	        }
			

	        //往下一個Lifecycle Stage
	        Resolution resolution = context.proceed();
	        
	        
	        if (LifecycleStage.ActionBeanResolution.equals(context.getLifecycleStage()))
	        {
	        	if (context.getActionBean() != null) {
	        		ActionBean actionBean = context.getActionBean();
	        		actionLog.setActionBeanClass(actionBean.getClass().getSimpleName());
	        		actionLog.setActionName(menuLoader.getActionNameByBeanClass(actionLog.getActionBeanClass()));
	        		actionLog.setParentActionName(menuLoader.getParentActionNameByBeanClass(actionLog.getActionBeanClass()));
	        	}
	        }
	        else if (LifecycleStage.HandlerResolution.equals(context.getLifecycleStage()))
	        {
	        	if (null != context.getHandler())
	        	{
	        		actionLog.setEventName(context.getHandler().getName());
	        	}
	        }
	        

	        return resolution;
		
	}
	
	private void log(ActionLog accessLog)
	{
		try {
			ActionLogService accessLogService = (ActionLogService)SpringContextUtil.getBean("actionLogService");
            accessLogService.addctionLog(accessLog);			
		} catch (Exception e) {
			logger.error("儲存使用者操作紀錄至DB發生錯誤:", e);
		}
	}

}
